package com.idea.dsl.controller;

import com.idea.dsl.model.DslResponse;
import com.idea.dsl.service.BusinessRuleParserService;
import com.idea.dsl.service.ExcelProcessingService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务规则控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/business-rule")
@RequiredArgsConstructor
@Validated
public class BusinessRuleController {
    
    private final BusinessRuleParserService businessRuleParserService;
    private final ExcelProcessingService excelProcessingService;
    
    /**
     * 解析单个业务规则
     */
    @PostMapping("/parse")
    public ResponseEntity<DslResponse> parseBusinessRule(@Valid @RequestBody BusinessRuleRequest request) {
        log.info("收到业务规则解析请求: {}", request.getRuleName());
        
        try {
            DslResponse response = businessRuleParserService.parseBusinessRule(
                request.getRuleName(),
                request.getRelatedField(),
                request.getRuleDescription()
            );
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("业务规则解析异常", e);
            return ResponseEntity.internalServerError()
                    .body(DslResponse.builder()
                            .status(DslResponse.GenerationStatus.FAILED)
                            .errorMessage("业务规则解析失败: " + e.getMessage())
                            .build());
        }
    }
    
    /**
     * 批量解析业务规则
     */
    @PostMapping("/parse-batch")
    public ResponseEntity<Map<String, Object>> parseBatchBusinessRules(@Valid @RequestBody BatchBusinessRuleRequest request) {
        log.info("收到批量业务规则解析请求，规则数量: {}", request.getRules().size());
        
        try {
            Map<String, Map<String, String>> rulesData = new HashMap<>();
            
            for (int i = 0; i < request.getRules().size(); i++) {
                BusinessRuleRequest rule = request.getRules().get(i);
                String ruleId = "rule-" + (i + 1);
                
                Map<String, String> ruleData = new HashMap<>();
                ruleData.put("ruleName", rule.getRuleName());
                ruleData.put("relatedField", rule.getRelatedField());
                ruleData.put("ruleDescription", rule.getRuleDescription());
                
                rulesData.put(ruleId, ruleData);
            }
            
            Map<String, DslResponse> results = businessRuleParserService.parseBatchBusinessRules(rulesData);
            
            // 统计结果
            long successCount = results.values().stream()
                    .mapToLong(r -> r.getStatus() == DslResponse.GenerationStatus.SUCCESS ? 1 : 0)
                    .sum();
            
            Map<String, Object> response = new HashMap<>();
            response.put("total", results.size());
            response.put("success", successCount);
            response.put("failed", results.size() - successCount);
            response.put("results", results);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("批量业务规则解析异常", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "批量解析失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(errorResponse);
        }
    }
    
    /**
     * 上传Excel文件解析业务规则
     */
    @PostMapping("/upload-excel")
    public ResponseEntity<Map<String, Object>> uploadExcelBusinessRules(@RequestParam("file") MultipartFile file) {
        log.info("收到Excel文件上传请求: {}", file.getOriginalFilename());

        try {
            // 验证文件
            if (file.isEmpty()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("error", "上传的文件为空");
                return ResponseEntity.badRequest().body(errorResponse);
            }

            if (!isExcelFile(file)) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("error", "请上传Excel文件(.xls或.xlsx格式)");
                return ResponseEntity.badRequest().body(errorResponse);
            }

            // 解析Excel文件
            List<ExcelProcessingService.BusinessRuleData> excelData =
                excelProcessingService.parseExcelToBusinessRules(file);

            if (excelData.isEmpty()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("error", "Excel文件中未找到有效的业务规则数据");
                return ResponseEntity.badRequest().body(errorResponse);
            }

            // 转换为批量处理格式
            Map<String, Map<String, String>> rulesData = new HashMap<>();
            for (int i = 0; i < excelData.size(); i++) {
                ExcelProcessingService.BusinessRuleData ruleData = excelData.get(i);
                String ruleId = "excel-rule-" + (i + 1);

                Map<String, String> ruleMap = new HashMap<>();
                ruleMap.put("ruleName", ruleData.getRuleName());
                ruleMap.put("relatedField", ruleData.getRelatedField());
                ruleMap.put("ruleDescription", ruleData.getRuleDescription());

                rulesData.put(ruleId, ruleMap);
            }

            // 批量解析
            Map<String, DslResponse> results = businessRuleParserService.parseBatchBusinessRules(rulesData);

            // 生成汇总报告
            Map<String, Object> response = generateSummaryReport(results);
            response.put("originalDataCount", excelData.size());
            response.put("filename", file.getOriginalFilename());

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Excel文件处理异常", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "Excel文件处理失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(errorResponse);
        }
    }

    /**
     * 从Excel数据解析业务规则
     */
    @PostMapping("/parse-excel")
    public ResponseEntity<Map<String, Object>> parseExcelBusinessRules(@Valid @RequestBody ExcelBusinessRuleRequest request) {
        log.info("收到Excel业务规则解析请求，数据行数: {}", request.getData().size());
        
        try {
            Map<String, Map<String, String>> rulesData = new HashMap<>();
            
            for (int i = 0; i < request.getData().size(); i++) {
                ExcelRowData row = request.getData().get(i);
                String ruleId = "excel-rule-" + (i + 1);
                
                Map<String, String> ruleData = new HashMap<>();
                ruleData.put("ruleName", row.getRuleName());
                ruleData.put("relatedField", row.getRelatedField());
                ruleData.put("ruleDescription", row.getRuleDescription());
                
                rulesData.put(ruleId, ruleData);
            }
            
            Map<String, DslResponse> results = businessRuleParserService.parseBatchBusinessRules(rulesData);
            
            // 生成汇总报告
            Map<String, Object> response = generateSummaryReport(results);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Excel业务规则解析异常", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "Excel解析失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(errorResponse);
        }
    }
    
    /**
     * 生成汇总报告
     */
    private Map<String, Object> generateSummaryReport(Map<String, DslResponse> results) {
        Map<String, Object> report = new HashMap<>();
        
        long totalCount = results.size();
        long successCount = results.values().stream()
                .mapToLong(r -> r.getStatus() == DslResponse.GenerationStatus.SUCCESS ? 1 : 0)
                .sum();
        long failedCount = totalCount - successCount;
        
        // 基本统计
        report.put("summary", Map.of(
            "total", totalCount,
            "success", successCount,
            "failed", failedCount,
            "successRate", totalCount > 0 ? (double) successCount / totalCount * 100 : 0
        ));
        
        // 详细结果
        report.put("results", results);
        
        // 失败原因统计
        Map<String, Long> failureReasons = new HashMap<>();
        results.values().stream()
                .filter(r -> r.getStatus() != DslResponse.GenerationStatus.SUCCESS)
                .forEach(r -> {
                    String reason = r.getErrorMessage() != null ? r.getErrorMessage() : "未知错误";
                    failureReasons.merge(reason, 1L, Long::sum);
                });
        report.put("failureReasons", failureReasons);
        
        return report;
    }

    /**
     * 验证是否为Excel文件
     */
    private boolean isExcelFile(MultipartFile file) {
        String filename = file.getOriginalFilename();
        if (filename == null) {
            return false;
        }

        String contentType = file.getContentType();
        return filename.toLowerCase().endsWith(".xls") ||
               filename.toLowerCase().endsWith(".xlsx") ||
               "application/vnd.ms-excel".equals(contentType) ||
               "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".equals(contentType);
    }
    
    /**
     * 业务规则请求模型
     */
    @Data
    public static class BusinessRuleRequest {
        @NotBlank(message = "规则名称不能为空")
        private String ruleName;
        
        private String relatedField;
        
        @NotBlank(message = "规则描述不能为空")
        private String ruleDescription;
    }
    
    /**
     * 批量业务规则请求模型
     */
    @Data
    public static class BatchBusinessRuleRequest {
        @Valid
        private List<BusinessRuleRequest> rules;
    }
    
    /**
     * Excel业务规则请求模型
     */
    @Data
    public static class ExcelBusinessRuleRequest {
        @Valid
        private List<ExcelRowData> data;
    }
    
    /**
     * Excel行数据模型
     */
    @Data
    public static class ExcelRowData {
        private String ruleName;
        private String relatedField;
        private String ruleDescription;
    }
}
